package org.util;

import java.sql.*;


public class DButil {

    private static final String username = "root" ;
    private static final String password = "20001110y" ;

    private static final String url ="jdbc:mysql://localhost:3306/test01?" +
            "useUnicode=true&characterEncoding=utf8&serverTimezone=UTC";

    private static final String driver = "com.mysql.cj.jdbc.Driver" ;

    /**
     * 静态代码块，加载驱动程序
     */
    static {

        try {
            Class.forName(driver) ;
        } catch (ClassNotFoundException e) {
            System.out.print("加载驱动程序失败！") ;
            e.printStackTrace();
        }
    }

    /**
     * 返回连接对象
     * @return
     */
    public static Connection getConnection(){
        Connection conn = null ;

        try {
            conn = DriverManager.getConnection(url,username,password) ;
        } catch (SQLException throwables) {
            System.out.print("获取连接对象失败！") ;
            throwables.printStackTrace();
        }
        return conn ;
    }

    /**
     * 关闭数据库对象，释放资源
     * @param rs
     * @param stmt
     * @param conn
     */
    public static void close(ResultSet rs, Statement stmt,Connection conn){

        if(conn!=null){
            try {
                conn.close();
            } catch (SQLException throwables) {
                System.out.print("关闭连接失败！") ;
                throwables.printStackTrace();
            }
        }

        if(stmt!=null){
            try {
                stmt.close();
            } catch (SQLException throwables) {
                System.out.print("关闭语句对象失败！") ;
                throwables.printStackTrace();
            }
        }

        if(rs!=null){
            try {
                rs.close() ;
            } catch (SQLException throwables) {
                System.out.print("关闭结果集对象失败！") ;
                throwables.printStackTrace();
            }
        }

    }

    /**
     * 定义主方法，测试是否连接成功
     * @param args
     */
    public static void main(String[] args){

        System.out.print(DButil.getConnection()) ;
    }
}
